home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16145 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  77 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: RossBoylan@aol.com (Ross Boylan)
  3. Newsgroups: comp.lang.c++
  4. Subject: Mutually referring header files
  5. Date: Tue, 09 Apr 1996 19:22:49 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4ked7q$8g3@dub-news-svc-1.compuserve.com>
  8. NNTP-Posting-Host: ad06-115.compuserve.com
  9. X-Newsreader: Forte Free Agent 1.0.82
  10.  
  11. I have 2 classes A + B, defined in separate files.  Each refers to and
  12. messages the other.  What is the best way to handle this?
  13.  
  14. 1) My naive approach was
  15. a.h----------------------------------------------------------
  16. #ifndef ah
  17. #define ah
  18. #include "b.h:
  19. class A {
  20. public:
  21.     void hello();
  22. private:
  23.     B *pB;
  24. //etc
  25. };
  26. #endif
  27.  
  28. b.h------------------------------------------------------------
  29. #ifndef bh
  30. #define bh
  31. #include "a.h"
  32. class B{
  33. public:
  34.     void hello();
  35. private:
  36.     A *pA;
  37. };
  38. #endif
  39. -------------------------------------------------------------------
  40. The #ifndef's prevent infinite recursion, but if we start with
  41. #include "a.h"
  42. this will then include "b.h"
  43. b.h will skip a.h since the symbol ah is already defined.
  44. So when we get to the line A *pA in b.h, A has not yet been defined
  45. and we get an error.
  46.  
  47. 2) My less naive approach was to add the declaration
  48. class A;
  49. to b.h.  This works, but seems awfully obscure, since on the face of
  50. it the code 
  51. "include a.h"
  52. class A; 
  53. is redundant.
  54. Also when you multiply this by a bunch of classes referencing each
  55. other, it gets pretty messy.  In particular if you add a subclass of A
  56. to the a.h file, and then want to refer to it from elsewhere, you must
  57. add the declaration for this class to all the consumers.
  58.  
  59.  
  60. 3) It may or may not matter that I'm actually using smart pointers, so
  61. the pointer declarations are actually
  62. CountedObjPtr<A> pA;
  63.  
  64. 4) 
  65. Also, I put no code definition in the header file (i.e., b.h contains
  66. no lines of the form
  67. class B {
  68.     void doit() {pA->hello();};
  69. };
  70. Such lines require more than class A;--they must actually know the
  71. protocols A responds to.
  72.  
  73. This bit of code discipline is possible for regular classes, but what
  74. do I do for templates.  With my compiler (MSVC++ 4.0) the header file
  75. must include all the code definition.
  76.  
  77.